package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.WeiboMapper;
import com.tedu.weibo.pojo.dto.WeiboDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.entity.Weibo;
import com.tedu.weibo.pojo.vo.WeiboDetailVO;
import com.tedu.weibo.pojo.vo.WeiboVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/v1/weibo")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @PostMapping("/insert")
    public int insert(@RequestBody WeiboDTO weiboDTO, HttpSession session) {
        log.info("WeiboController.insert,发表微博");
        log.trace("开始执行insert()方法");
        log.debug("weiboDTO:"+weiboDTO);
        User user = (User) session.getAttribute("user");
        log.info("通过session获取用户登录信息");
        log.debug("user:"+user);
        if (user == null) {//未登录
            log.trace("user为null，用户未登录");
            return 2;
        } else {
            log.trace("user不为null，处理发表微博");
            Weibo weibo = new Weibo();
            BeanUtils.copyProperties(weiboDTO,weibo);
            weibo.setCreated(new Date());
            weibo.setUserId(user.getId());
            log.debug("weibo:"+weibo);
            weiboMapper.insert(weibo);
            log.trace(user.getNickname()+"发表微博");
            return 1;
        }
    }

    @GetMapping("/selectIndex")
    public List<WeiboVO> selectIndex() {
        List<WeiboVO> weiboVOList = weiboMapper.selectIndex();
         return weiboVOList;
    }

    @GetMapping("/selectById")
    public WeiboDetailVO selectDetail(Integer id) {
        return weiboMapper.selectById(id);
    }

}
